﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Server.Search.Administration;
using Microsoft.Office.Server;

namespace SearchAdminToolkit.UI.Controls
{
    /// <summary>
    /// Defines a class for working with <see cref="RankingParameter"/> objects in SharePoint.
    /// </summary>
    class RankingManager
    {

        /// <summary>
        /// Gets a Ranking object.
        /// </summary>
        /// <returns></returns>
        public static Ranking GetRanking()
        {
            return new Ranking(SearchContext.GetContext(ServerContext.Default));
        }

        /// <summary>
        /// Finds all <see cref="RankingParameter"/> objects.
        /// </summary>
        /// <returns></returns>
        public static List<RankingParameter> FindAll()
        {
            Ranking rank = GetRanking();
            return (from RankingParameter rp in rank.RankingParameters orderby rp.Name ascending select rp).ToList<RankingParameter>();
        }

        /// <summary>
        /// Updates the value of an existing <see cref="RankingParameter"/>.
        /// </summary>
        /// <param name="rankingParamKey"></param>
        /// <param name="rankingParamValue"></param>
        public static void Update(string rankingParamKey, float rankingParamValue)
        {
            Ranking rank = GetRanking();

            RankingParameter param = rank.RankingParameters[rankingParamKey];

            if (param != null)
            {
                param.Value = rankingParamValue;
            }

            rank.StartRankingUpdate(RankingUpdateType.FullUpdate);

        }

        /// <summary>
        /// Starts a ranking update request.
        /// </summary>
        public static void StartRankingUpdate()
        {
            Ranking rank = GetRanking();

            rank.StartRankingUpdate(RankingUpdateType.FullUpdate);
        }
    }
}
